package org.fin.minicat.responce;

import org.fin.minicat.protocol.HttpStatusCode;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.Objects;

public abstract class ResponceUtils {

  /**
   * 向SocketChannel写入响应信息
   * @param responce        包含响应信息的Responce对象
   * @param socketChannel   要写入数据的SocketChannel对象
   */
  public static void respon(Responce responce, SocketChannel socketChannel) throws IOException {
    Objects.requireNonNull(responce, "Responce不能为空");
    Objects.requireNonNull(socketChannel, "SocketChannel不能为空");

    HttpResponceHeader header = responce.getHttpResponceHeader();
    Objects.requireNonNull(header, "返回响应之前必须设置http header");

    byte[] content = responce.getContent();
    ByteBuffer buffer;
    if (content != null && content.length > 0) {
      byte[] headerBytes = header.toString().getBytes();
      buffer = ByteBuffer.allocate(headerBytes.length + content.length);
      buffer.put(headerBytes);
      buffer.put(content);
      buffer.flip();
    } else {
      buffer = ByteBuffer.wrap(header.toString().getBytes());
    }

    socketChannel.write(buffer);
  }


  /**
   * 根据给定的字节数组，构造一个200 ok的Responce对象
   * @param content   要返回的响应体数据
   * @return          返回200的Responce对象
   */
  public static Responce okResponce(byte[] content) {
    Responce responce = new Responce();
    responce.setHttpResponceHeader(okResponceHeader());
    responce.setContent(content);
    return responce;
  }

  /**
   * 将传入的responce对象改造成一个404的Responce对象
   * @param responce  原Responce对象
   */
  public static void notFoundResponce(Responce responce) {
    Objects.requireNonNull(responce, "Responce对象不能为空，404 Responce对象改造失败");

    byte[] content = "<h1>404 NOT FOUND</h1>".getBytes();
    responce.setHttpResponceHeader(notFoundResponceHeader());
    responce.setContent(content);
  }

  /**
   * 构造一个200的响应头HttpResponceHeader对象
   * @return    200的响应头HttpResponceHeader对象
   */
  public static HttpResponceHeader okResponceHeader() {
    HttpResponceHeader header = new HttpResponceHeader();
    header.setProtocol("HTTP/1.1");
    header.setStatusCode(HttpStatusCode.OK);
    header.setContentType("text/html");
    header.setCharset(StandardCharsets.UTF_8);
    return header;
  }

  /**
   * 构造一个404的响应头HttpResponceHeader对象
   * @return    404的响应头HttpResponceHeader对象
   */
  public static HttpResponceHeader notFoundResponceHeader() {
    HttpResponceHeader header = new HttpResponceHeader();
    header.setProtocol("HTTP/1.1");
    header.setStatusCode(HttpStatusCode.NOT_FOUND);
    header.setContentType("text/html");
    header.setCharset(StandardCharsets.UTF_8);
    return header;
  }
}
